<template>
  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <a-row :gutter="24">
        <a-col :span="10">
          <a-space size="small">
            <a-button type="primary" @click="add">
              新增
            </a-button>
          </a-space>
          <a-table v-if="level1.length>0"
                   :columns="columns"
                   :row-key="record => record.id"
                   :data-source="level1"
                   :loading="loading"
                   :pagination="false"
                   size="small"
                   :default-expand-all-rows="true">
            <template #name="{ text, record }">
              {{ record.sort }} {{ text }}
            </template>
            <template v-slot:action="{ text, record}">
              <a-space size="small">
                <a-button type="primary" @click="edit(record)" size="small">
                  编辑
                </a-button>
                <a-popconfirm
                    title="该删除操作不可逆-确定删除吗?"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="handleDelete(record.id)"
                >
                  <a-button type="primary" danger size="small">
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table>
        </a-col>
        <a-col :span="14">
          <p>
            <a-form layout="inline" :model="param">
              <a-button type="primary" @click="handleSave()">
                保存
              </a-button>
            </a-form>
          </p>
          <a-form :model="doc" :label-col="{ span : 6}" layout="vertical">
            <a-form-item>
              <a-input v-model:value="doc.name" placeholder="请输入名称"/>
            </a-form-item>
            <a-form-item>
              <a-tree-select
                  v-model:value="doc.parent"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="treeSelectLevel1"
                  placeholder="请选择父文档"
                  tree-default-expand-all
                  :replaceFields="{title:'name', key:'id', value:'id'}"
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item>
              <a-input v-model:value="doc.sort" placeholder="请选择排序权重"/>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handlePreviewContent()">
                <EyeOutlined/> 内容预览
              </a-button>
            </a-form-item>
            <a-form-item>
              <div id="content"></div>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-drawer width="1000" placement="right" :closable="false" :visible="drawerVisible" @close="onDrawerClose">
        <div class="wangeditor" :innerHTML="previewHtml"></div>
      </a-drawer>
    </a-layout-content>
  </a-layout>
</template>

<script lang="ts">
import {defineComponent, onMounted, ref} from 'vue';
import axios from "axios";
import {message} from 'ant-design-vue'
import {Tool} from "@/util/tool";
import {useRoute} from "vue-router";
import E from "wangeditor";

export default defineComponent({
  name: 'AdminDoc',
  setup() {
    const editor = new E('#content');
    editor.config.zIndex = 0;

    let ids: Array<string> = [];
    const route = useRoute();

    // 文档信息响应式对象
    const docs = ref();
    // 表示加载状态
    const loading = ref(false);
    // 表格列信息
    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
        slots: {customRender: 'name'}
      },
      {
        title: 'Action',
        key: 'action',
        slots: {customRender: 'action'},
      },
    ];

    const level1 = ref();
    level1.value = [];
    const treeSelectLevel1 = ref();
    treeSelectLevel1.value = [];
    /**
     * 数据查询
     */
    const handleQuery = () => {
      loading.value = true;
      axios.get("/doc/list/" + route.query.ebookId).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          level1.value = [];
          level1.value = Tool.array2Tree(data.content, 0);
          // 加载父节点选择下拉框内容
          if (level1.value.length != 0) {
            treeSelectLevel1.value = Tool.copy(level1.value);
            treeSelectLevel1.value.unshift({id: 0, name: "无"});
          } else {
            treeSelectLevel1.value = [{id: 0, name: "无"}];
          }
        } else {
          message.error(data.message);
        }
      })
    };

    // 表单
    const doc = ref();
    doc.value = {};
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    const handleSave = () => {
      modalLoading.value = true;
      doc.value.ebookId = route.query.ebookId;
      doc.value.content = editor.txt.html();
      // 编辑保存文档
      axios.post("/doc/save", doc.value).then((response) => {
        modalLoading.value = true;
        loading.value = false;
        const data = response.data;
        if (data.success) {
          modalVisible.value = false;
          modalLoading.value = false;
          message.success("操作成功")
          handleQuery();
        } else {
          modalLoading.value = false;
          message.error(data.message)
        }
      })
    };

    /**
     * 内容查询
     */
    const handleQueryContent = () => {
      axios.get("/doc/findContent/" + doc.value.id).then((response) => {
        const data = response.data;
        if (data.success) {
          editor.txt.html(data.content);
        } else {
          message.error(data.message);
        }
      })
    };

    /**
     * 将节点以及子孙节点置disabled
     */
    const setDisable = (treeSelectLevel1: any, id: any) => {
      for (let i = 0; i < treeSelectLevel1.length; ++i) {
        const node = treeSelectLevel1[i];
        if (node.id === id) {
          node.disabled = true;
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; ++j) {
              setDisable(children, children[j].id);
            }
          }
        } else {
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            setDisable(children, id);
          }
        }
      }
    };

    // 编辑文档方法
    const edit = (record: any) => {
      modalVisible.value = true;
      doc.value = Tool.copy(record);
      handleQueryContent();
      // 关闭当前节点及其所有子孙节点的选择项，并添加一项无，表示根节点
      treeSelectLevel1.value = Tool.copy(level1.value);
      setDisable(treeSelectLevel1.value, record.id);
      treeSelectLevel1.value.unshift({id: 0, name: "无"});
    }

    // 新增文档方法
    const add = () => {
      modalVisible.value = true;
      doc.value = {
        ebookId: route.query.ebookId,
      };
      editor.txt.html("");
    }

    /**
     * 将节点以及子孙节点数据加入ids数组中
     */
    const getNode = (treeSelectLevel1: any, id: any) => {
      for (let i = 0; i < treeSelectLevel1.length; ++i) {
        const node = treeSelectLevel1[i];
        if (node.id === id) {
          ids.push(id);
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; ++j) {
              getNode(children, children[j].id);
            }
          }
        } else {
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            getNode(children, id);
          }
        }
      }
    };

    // 删除文档方法
    const handleDelete = (id: number) => {
      ids = [];
      getNode(level1.value, id);
      axios.delete("/doc/delete/" + ids.join(",")).then((response) => {
        const data = response.data;
        if (data.success) {
          message.success("操作成功")
          handleQuery();
        }
      })
    };

    // 富文本内容预览
    const drawerVisible = ref(false);
    const previewHtml = ref();
    const handlePreviewContent = () => {
      previewHtml.value = editor.txt.html();
      drawerVisible.value = true;
    };
    const onDrawerClose = () => {
      drawerVisible.value = false;
    };


    onMounted(() => {
      handleQuery();
      editor.create();
      console.log(doc);
    });
    return {
      docs,
      doc,
      loading,
      columns,
      modalVisible,
      modalLoading,
      edit,
      add,
      handleSave,
      handleDelete,
      level1,
      treeSelectLevel1,
      handlePreviewContent,
      drawerVisible,
      previewHtml,
      onDrawerClose

    }
  }
});

</script>
